package com.tpsix.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tpsix.util.R;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败处理器
 */
@Slf4j
@Component
@AllArgsConstructor
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        log.error("Responding with unauthorized error. Message:{}, url:{}", e.getMessage(), request.getRequestURI());
        String json = objectMapper.writeValueAsString(R.error(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"));
        R.responseWrite(response, json, HttpServletResponse.SC_UNAUTHORIZED);
    }

}
